import api from './api';

// 班级类型定义
export interface Class {
  id: number;
  name: string;
  grade: string;
  teacher?: {
    id: number;
    username: string;
    name: string;
    phone?: string;
    email?: string;
    avatar?: string | null;
    role: string;
    enabled: boolean;
    createTime: string;
    updateTime?: string;
  };
  capacity?: number | null;
  currentCount?: number | null;
  remarks?: string;
  enabled?: boolean;
  createTime: string;
  updateTime?: string;
}

// 分页响应接口
export interface PageResponse<T> {
  content: T[];
  pageable: {
    pageNumber: number;
    pageSize: number;
    sort: {
      empty: boolean;
      sorted: boolean;
      unsorted: boolean;
    };
    offset: number;
    paged: boolean;
    unpaged: boolean;
  };
  last: boolean;
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  sort: {
    empty: boolean;
    sorted: boolean;
    unsorted: boolean;
  };
  numberOfElements: number;
  first: boolean;
  empty: boolean;
}

// 查询参数类型
export interface ClassQueryParams {
  page?: number;
  size?: number;
  name?: string;
  grade?: string;
  keyword?: string;
}

// 创建班级参数类型
export interface CreateClassParams {
  name: string;
  grade: string;
  capacity?: number | null;
  currentCount?: number | null;
  remarks?: string;
}

// 更新班级参数类型
export interface UpdateClassParams {
  name?: string;
  grade?: string;
  capacity?: number | null;
  currentCount?: number | null;
  remarks?: string;
}

// 分配教师参数类型
export interface AssignTeacherParams {
  teacherId: number;
}

// 班级列表项类型
interface ClassListItem {
  id: number;
  name: string;
  grade: string;
  teacherName: string;
}

// 班级列表响应类型
interface ClassListResponse {
  data: ClassListItem[];
  message: string;
  status: string;
}

// API响应格式
interface ApiResponse<T> {
  status: string;
  message: string;
  data: T;
}

/**
 * 获取班级列表
 * @param params 查询参数
 * @returns 班级列表分页数据
 */
export const getClasses = async (params: ClassQueryParams = {}): Promise<PageResponse<Class>> => {
  try {
    const { page = 0, size = 10, name, grade, keyword } = params;
    
    // 构建查询参数
    const queryParams: Record<string, any> = { page, size };
    
    // 优先使用keyword进行搜索，如果没有keyword则使用name和grade
    if (keyword) {
      queryParams.keyword = keyword;
    } else {
      if (name) queryParams.name = name;
      if (grade) queryParams.grade = grade;
    }
    
    console.log('班级查询参数:', queryParams);
    
    const response = await api.get<any>('/admin/classes', {
      params: queryParams
    });
    
    console.log('获取班级列表数据:', response);
    
    // 处理API响应
    if (response && response.data) {
      // 如果是标准API响应格式
      const classes = response.data;
      
      // 构造PageResponse对象
      const pageResponse: PageResponse<Class> = {
        content: classes,
        pageable: {
          pageNumber: page,
          pageSize: size,
          sort: {
            empty: false,
            sorted: true,
            unsorted: false
          },
          offset: page * size,
          paged: true,
          unpaged: false
        },
        last: true,
        totalElements: classes.length,
        totalPages: Math.ceil(classes.length / size),
        size: size,
        number: page,
        sort: {
          empty: false,
          sorted: true,
          unsorted: false
        },
        numberOfElements: classes.length,
        first: page === 0,
        empty: classes.length === 0
      };
      
      return pageResponse;
    } else if (response && response.content) {
      // 如果直接返回分页对象
      return response;
    } else {
      // 默认返回空数据
      console.warn('班级列表数据格式不符合预期');
      return {
        content: [],
        pageable: {
          pageNumber: page,
          pageSize: size,
          sort: { empty: true, sorted: false, unsorted: true },
          offset: page * size,
          paged: true,
          unpaged: false
        },
        last: true,
        totalElements: 0,
        totalPages: 0,
        size: size,
        number: page,
        sort: { empty: true, sorted: false, unsorted: true },
        numberOfElements: 0,
        first: true,
        empty: true
      };
    }
  } catch (error) {
    console.error('获取班级列表失败:', error);
    throw error;
  }
};

/**
 * 获取所有班级列表
 * @returns 班级列表
 */
export const getAllClasses = async (): Promise<Class[]> => {
  try {
    const response = await api.get<ApiResponse<Class[]>>('/admin/classes');
    console.log('获取所有班级列表数据:', response);
    return response || [];
  } catch (error) {
    console.error('获取所有班级列表失败:', error);
    throw error;
  }
};

/**
 * 获取班级列表(供创建学生/更新学生选择)
 * @returns 可选班级列表
 */
export const getClassList = async (): Promise<ClassListItem[]> => {
  try {
    // 尝试获取班级列表
    const response = await api.get<any>('/admin/classes/list');
    console.log('获取班级列表数据:', response);
    
    // 检查响应格式
    if (response.data) {
      // 如果是标准API响应格式
      if (response.data.data && Array.isArray(response.data.data)) {
        return response.data.data;
      }
      
      // 如果是直接返回的数组
      if (Array.isArray(response.data)) {
        return response.data;
      }
      
      // 如果是分页格式
      if (response.data.content && Array.isArray(response.data.content)) {
        return response.data.content.map((cls: any) => ({
          id: cls.id,
          name: cls.name,
          grade: cls.grade,
          teacherName: cls.teacher ? cls.teacher.name : ''
        }));
      }
    }
    
    // 默认返回空数组
    console.warn('班级列表数据格式不符合预期');
    return [];
  } catch (error) {
    console.error('获取班级列表失败:', error);
    return [];
  }
};

/**
 * 创建班级
 * @param params 班级信息
 * @returns 创建的班级信息
 */
export const createClass = async (params: CreateClassParams): Promise<Class> => {
  try {
    const response = await api.post<ApiResponse<Class>>('/admin/classes', params);
    console.log('创建班级结果:', response.data);
    return response.data.data;
  } catch (error) {
    console.error('创建班级失败:', error);
    throw error;
  }
};

/**
 * 更新班级信息
 * @param id 班级ID
 * @param params 更新的班级信息
 * @returns 更新后的班级信息
 */
export const updateClass = async (id: number, params: UpdateClassParams): Promise<Class> => {
  try {
    const response = await api.put<ApiResponse<Class>>(`/admin/classes/${id}`, params);
    console.log('更新班级结果:', response.data);
    return response.data.data;
  } catch (error) {
    console.error('更新班级失败:', error);
    throw error;
  }
};

/**
 * 删除班级
 * @param id 班级ID
 * @returns 是否成功
 */
export const deleteClass = async (id: number): Promise<boolean> => {
  try {
    await api.delete(`/admin/classes/${id}`);
    console.log('删除班级成功');
    return true;
  } catch (error) {
    console.error('删除班级失败:', error);
    throw error;
  }
};

/**
 * 分配教师到班级
 * @param classId 班级ID
 * @param teacherId 教师ID
 * @returns 是否成功
 */
export const assignTeacherToClass = async (classId: number, teacherId: number): Promise<boolean> => {
  try {
    console.log(`开始分配教师(ID:${teacherId})到班级(ID:${classId})`);
    const params: AssignTeacherParams = { teacherId };
    console.log('请求参数:', params);
    console.log('请求URL:', `/admin/classes/${classId}/teacher`);
    
    const response = await api.put(`/admin/classes/${classId}/teacher`, params);
    console.log('分配教师到班级响应:', response);
    
    if (response.status >= 200 && response.status < 300) {
      console.log('分配教师到班级成功');
      return true;
    } else {
      console.error('分配教师到班级失败，状态码:', response.status);
      return false;
    }
  } catch (error) {
    console.error('分配教师到班级失败:', error);
    if (error.response) {
      console.error('错误响应数据:', error.response.data);
      console.error('错误状态码:', error.response.status);
    }
    throw error;
  }
}; 